<?php
/**
* @file $Id: Grades.php 542 2007-06-03 22:01:02Z focus-sis $
* @package Focus/SIS
* @copyright Copyright (C) 2006 Andrew Schmadeke. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
* Focus/SIS is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/

$user_mp = UserMP();
$all_mp = GetAllMP('QTR',UserMP());
$user_staff_id = User('STAFF_ID');
$user_username = User('USERNAME');
$course_period_id = UserCoursePeriod();
$user_gradebook_sort_pref = Preferences('ASSIGNMENT_SORTING', 'Gradebook');

$course_id = DBGetValue("
		SELECT        COURSE_ID as VALUE
		FROM          COURSE_PERIODS 
		WHERE         COURSE_PERIOD_ID = '$course_period_id'
		");

$types_RET = DBGet(DBQuery("
		SELECT        ASSIGNMENT_TYPE_ID
		 ,            TITLE 
		FROM          GRADEBOOK_ASSIGNMENT_TYPES 
		WHERE         STAFF_ID = '$user_staff_id' 
		AND           COURSE_ID = '$course_id' 
		ORDER BY      TITLE
		"));

include ($staticpath . 'ProgramFunctions/_makeLetterGrade.fnc.php');

if ( ($_REQUEST['assignment_id'] 
&& $_REQUEST['assignment_id'] != 'student' ) 
&& !$_REQUEST['values']
){
	unset($_SESSION['student_id']);
	unset($_REQUEST['student_id']);
}

if ($_REQUEST['assignment_id'] != 'totals') {
	unset($_SESSION['_REQUEST_vars']['assignment_id']);
}

$_FOCUS['allow_edit'] = true;

$config_RET = DBGet(DBQuery("
		SELECT        TITLE
		 ,            VALUE 
		FROM          PROGRAM_USER_CONFIG 
		WHERE         USERNAME = '$user_username' 
		AND           PROGRAM = 'Gradebook'
		"), array(), array('TITLE'));
		
if (count($config_RET)) {
	foreach ($config_RET as $title => $value) {
		$programconfig[$title] = $value[1]['VALUE'];
	}
}

if ($_REQUEST['day_tables'] 
&& $_POST['day_tables']
){
	if ($_REQUEST['day_tables']['DUE_DATE'] 
	&& $_REQUEST['month_tables']['DUE_DATE'] 
	&& $_REQUEST['year_tables']['DUE_DATE']
	){
		$_REQUEST['tables']['DUE_DATE'] // =
				= $_REQUEST['day_tables']['DUE_DATE']
				. '-'
				. $_REQUEST['month_tables']['DUE_DATE']
				. '-'
				. $_REQUEST['year_tables']['DUE_DATE']
				;
	}
			
	if ($_REQUEST['day_tables']['ASSIGNED_DATE'] 
	&& $_REQUEST['month_tables']['ASSIGNED_DATE'] 
	&& $_REQUEST['year_tables']['ASSIGNED_DATE']
	){
		$_REQUEST['tables']['ASSIGNED_DATE'] // =
				= $_REQUEST['day_tables']['ASSIGNED_DATE']
				. '-'
				. $_REQUEST['month_tables']['ASSIGNED_DATE']
				. '-'
				. $_REQUEST['year_tables']['ASSIGNED_DATE']
				;
	}
	$_POST['tables'] = $_REQUEST['tables'];
}

if ($_REQUEST['tables'] 
&& $_POST['tables'] 
&& $_REQUEST['tables']['TITLE']
){
	if (!$_REQUEST['tables']['ASSIGNMENT_TYPE_ID']) {
		$id = DBGetValue("
				SELECT " . db_seq_nextval('GRADEBOOK_ASSIGNMENT_TYPES_SEQ') . "
				AS VALUE " .
				FROM_DUAL
				);

		$_REQUEST['tables']['ASSIGNMENT_TYPE_ID'] = $id;
		
		DBInsertInto( 'GRADEBOOK_ASSIGNMENT_TYPES'
				, array( 'ASSIGNMENT_TYPE_ID'  =>  $id
						, 'STAFF_ID'           =>  $user_staff_id
						, 'COURSE_ID'          =>  $course_id
						, 'TITLE'              =>  _('Assignments')
						)
				);
	}

	// INSERT INTO GRADEBOOK_ASSIGNMENTS 
	$id = DBGetValue("
			SELECT " . db_seq_nextval('GRADEBOOK_ASSIGNMENTS_SEQ') . "
			AS VALUE " . 
			FROM_DUAL
			);
			
	$column_values = array // (...)
			( 'ASSIGNMENT_ID'     => $id
			, 'STAFF_ID'          => $user_staff_id
			, 'MARKING_PERIOD_ID' => $user_mp
			);
	
	$go = false;
	
	if (!$_REQUEST['tables']['COURSE_ID'] 
	&& $_REQUEST['tables']['TITLE']
	){
		$_REQUEST['tables']['COURSE_ID'] = 'N';
	}
	
	foreach ($_REQUEST['tables'] as $column => $value) {
		if ($column == 'DUE_DATE' 
		|| $column == 'ASSIGNED_DATE'
		){
			if ($value && !VerifyDate($value)) {
				BackPrompt(_('Not all of the dates were entered correctly.'));
			}
		}
		
		elseif ($column == 'COURSE_ID' 
		&& $value == 'Y'
		){
			$value = $courseid;
		}
		elseif ($column == 'COURSE_ID') {		
			$column = 'COURSE_PERIOD_ID';
			$value = $course_period_id;
		}
		
		if ($value) {
			$column_values[$column] = $value;
			$go = true;
		}
	}

	if ($go) {
		DBInsertInto('GRADEBOOK_ASSIGNMENTS', $column_values);
	}
	
	unset($column_values);
	unset($go);		
	unset($_REQUEST['tables']);
	unset($_SESSION['_REQUEST_vars']['tables']);
	unset($_REQUEST['day_tables']);
	unset($_SESSION['_REQUEST_vars']['day_tables']);
}

$assignments_RET = DBGet(DBQuery("
		SELECT        ASSIGNMENT_ID
		 ,            TITLE
		 ,            POINTS 
		FROM          GRADEBOOK_ASSIGNMENTS 
		WHERE         STAFF_ID = '$user_staff_id' 
		 AND ( (      COURSE_ID = '$course_id' 
		   AND        STAFF_ID = '$user_staff_id' ) 
		  OR          COURSE_PERIOD_ID = '$course_period_id' ) 
		 AND          MARKING_PERIOD_ID = '$user_mp' 
		ORDER BY      $user_gradebook_sort_pref DESC
		"));

$LO_columns = array(  'FULL_NAME' => _('Student')
								.'<IMG SRC=assets/pixel_trans.gif width=150 height=1 border=0>'
					, 'STUDENT_ID' => _('Student ID')
					);
					
if (Preferences('DISPLAY_STUDENT_ID') != 'Y') {
	unset($LO_columns['STUDENT_ID']);
}

if ($_REQUEST['student_id'] 
|| $_REQUEST['assignment_id'] == 'student'
){
	$_SESSION['student_id'] = $_REQUEST['student_id'];
	
	echo '<script language=JavaScript>parent.side.location="'
			.$_SESSION['Side_PHP_SELF']
			.'?modcat="+parent.side.document.forms[0].modcat.value;</script>';	
	
	$_REQUEST['stuid'] = $_REQUEST['student_id'];
	
	$current_RET[$_REQUEST['student_id']] = DBGet(DBQuery("
			SELECT        g.ASSIGNMENT_ID
			 ,            g.POINTS 
			FROM          GRADEBOOK_GRADES g
			 ,            GRADEBOOK_ASSIGNMENTS a 
			WHERE         a.ASSIGNMENT_ID = g.ASSIGNMENT_ID 
			 AND          a.MARKING_PERIOD_ID = '$user_mp' 
			 AND          g.STUDENT_ID = '" . UserStudentID() . "' 
			 AND          g.COURSE_PERIOD_ID = '$course_period_id'
			"), array(), array('ASSIGNMENT_ID'));

	$extra['functions'] = array();
	foreach ($assignments_RET as $assignment) {
		$extra['SELECT'] .= ",'' AS G$assignment[ASSIGNMENT_ID]";
		$extra['functions'] += array('G'.$assignment['ASSIGNMENT_ID']=>'_makeExtraStuCols');
		$total_points[$assignment['ASSIGNMENT_ID']] = $assignment['POINTS'];
		$LO_columns += array('G'.$assignment['ASSIGNMENT_ID'] => "</b>" 
									. substr($assignment['TITLE'], 0, 6) 
									. "<br><b>(" . $assignment['POINTS'] . ")"
							);
	}
}
elseif ($_REQUEST['assignment_id'] == 'totals'){
	$extra['SELECT'] .= ",'' AS POINTS,'' AS LETTER_GRADE,'' AS COMMENT";
	$extra['functions'] = array //( ... )
			( 'POINTS' => '_makeExtraAssnCols'
			, 'LETTER_GRADE' => '_makeExtraAssnCols'
			);

	foreach ($types_RET as $type) {
		$extra['functions'] += 
				array( 'POINTS_' . $type['ASSIGNMENT_TYPE_ID'] => '_makeExtraAssnCols');
				
		$LO_columns += 
				array( 'POINTS_' . $type['ASSIGNMENT_TYPE_ID'] => $type['TITLE']);
				
		$extra['SELECT'] .= ",'' AS POINTS_" . $type['ASSIGNMENT_TYPE_ID'] . ' ';
	}

	$LO_columns += array
			( 'POINTS' => _('Total Points')
			, 'LETTER_GRADE' => _('Grade')
			);

	if ($programconfig['WEIGHT']=='Y')
		$LO_columns['LETTER_GRADE'] = _('Weighted Grade');

	$current_RET = DBGet(DBQuery("
			SELECT        g.STUDENT_ID
			 ,            sum(".db_case(array('g.POINTS',"'-1'","'0'",'g.POINTS')).") AS POINTS
			 ,            sum(".db_case(array('g.POINTS',"'-1'","'0'",'a.POINTS')).") AS TOTAL_POINTS 
			FROM          GRADEBOOK_GRADES g
			 ,            GRADEBOOK_ASSIGNMENTS a 
			WHERE         a.ASSIGNMENT_ID = g.ASSIGNMENT_ID 
			 AND          a.MARKING_PERIOD_ID = '$user_mp' 
			 AND          g.COURSE_PERIOD_ID = '$course_period_id' 
			 AND (        a.COURSE_PERIOD_ID = '$course_period_id' 
			  OR          a.COURSE_ID = '$course_id' ) 
			GROUP BY      g.STUDENT_ID
			"), array(), array('STUDENT_ID'));
			
	$current_types_RET = DBGet(DBQuery("
			SELECT        a.ASSIGNMENT_TYPE_ID
			 ,            g.STUDENT_ID
			 ,            sum(".db_case(array('g.POINTS',"'-1'","'0'",'g.POINTS')).") AS POINTS
			 ,            sum(".db_case(array('g.POINTS',"'-1'","'0'",'a.POINTS')).") AS TOTAL_POINTS 
			FROM          GRADEBOOK_GRADES g
			 ,            GRADEBOOK_ASSIGNMENTS a  
			WHERE         a.ASSIGNMENT_ID = g.ASSIGNMENT_ID 
			 AND          a.MARKING_PERIOD_ID = '$user_mp' 
			 AND          g.COURSE_PERIOD_ID = '$course_period_id' 
			 AND (        a.COURSE_PERIOD_ID = '$course_period_id' 
			  OR          a.COURSE_ID = '$course_id' ) 
			GROUP BY      g.STUDENT_ID
			 ,            a.ASSIGNMENT_TYPE_ID
			"), array(), array('STUDENT_ID', 'ASSIGNMENT_TYPE_ID'));

	if ($programconfig['WEIGHT'] == 'Y') {
		$percent_RET = DBGet(DBQuery("
				SELECT        gt.ASSIGNMENT_TYPE_ID
				 ,            gg.STUDENT_ID
				 ,            ".db_case( array
									( "sum(" . db_case( array 
											('gg.POINTS'
											,"'-1'"
											,"'0'"
											,'ga.POINTS'
											)).")"
									,"'0'"
									,"'0'"
									,"(sum(" . db_case( array
											('gg.POINTS'
											,"'-1'"
											,"'0'"
											,'gg.POINTS')).")
										 * gt.FINAL_GRADE_PERCENT 
										 / sum(" . db_case( array
										 		('gg.POINTS'
												,"'-1'"
												,"'0'"
												,'ga.POINTS'
												))."))"
									)) . " AS PARTIAL_PERCENT 
				FROM          GRADEBOOK_GRADES gg
				 JOIN         GRADEBOOK_ASSIGNMENTS ga
				  ON          ga.ASSIGNMENT_ID = gg.ASSIGNMENT_ID
				 JOIN         GRADEBOOK_ASSIGNMENT_TYPES gt
				  ON          gt.ASSIGNMENT_TYPE_ID = ga.ASSIGNMENT_TYPE_ID 
				WHERE         ga.MARKING_PERIOD_ID IN ($all_mp) 
				 AND          gg.COURSE_PERIOD_ID = '$course_period_id' 
				 AND          gt.COURSE_ID = '$course_id' 
				GROUP BY      gg.STUDENT_ID
				 ,            gt.ASSIGNMENT_TYPE_ID
				 ,            gt.FINAL_GRADE_PERCENT
				"), array(), array('STUDENT_ID', 'ASSIGNMENT_TYPE_ID'));
	}
	
	foreach ($assignments_RET as $assignment)
		$total_points[$assignment['ASSIGNMENT_ID']] = $assignment['POINTS'];
}
elseif ($_REQUEST['assignment_id']) {
	$extra['SELECT'] .= ",'' AS POINTS,'' AS LETTER_GRADE,'' AS COMMENT";
	
	$extra['functions'] = array
			( 'POINTS' => '_makeExtraAssnCols'
			, 'LETTER_GRADE' => '_makeExtraAssnCols'
			, 'COMMENT' => '_makeExtraAssnCols'
			);
			
	$LO_columns += array
			( 'POINTS' => _('Points')
			, 'LETTER_GRADE' => _('Grade')
			, 'COMMENT' => _('Comment')
			);
			
	$total_points = DBGetValue("
			SELECT        POINTS as VALUE
			FROM          GRADEBOOK_ASSIGNMENTS 
			WHERE         ASSIGNMENT_ID = '$_REQUEST[assignment_id]'
			");
			
	$current_RET = DBGet(DBQuery("
			SELECT        STUDENT_ID
			 ,            POINTS
			 ,            COMMENT
			 ,            ASSIGNMENT_ID 
			FROM          GRADEBOOK_GRADES 
			WHERE         ASSIGNMENT_ID = '$_REQUEST[assignment_id]' 
			 AND          COURSE_PERIOD_ID = '$course_period_id'
			"), array(), array('STUDENT_ID', 'ASSIGNMENT_ID'));
}
else {
	if ($_SESSION['student_id']) {
		unset($_SESSION['student_id']);
		echo '<script language=JavaScript>parent.side.location="'
				. $_SESSION['Side_PHP_SELF']
				. '?modcat="+parent.side.document.forms[0].modcat.value;</script>';	
	}
	
	$current_RET = DBGet(DBQuery("
			SELECT        g.STUDENT_ID
			 ,            g.ASSIGNMENT_ID
			 ,            g.POINTS 
			FROM          GRADEBOOK_GRADES g
			 JOIN         GRADEBOOK_ASSIGNMENTS a
			  ON          a.ASSIGNMENT_ID = g.ASSIGNMENT_ID
			WHERE         a.MARKING_PERIOD_ID = '$user_mp' 
			 AND          g.COURSE_PERIOD_ID = '$course_period_id'
			"), array(), array('STUDENT_ID', 'ASSIGNMENT_ID'));
				
	$count_extra = array('SELECT_ONLY' => 'ssm.STUDENT_ID');
	$count_students = GetStuList($count_extra);
	$count_students = count($count_students);

	$extra['functions'] = array();
	if (count($assignments_RET)) {
		if ($_FOCUS['direction'] == 'RTL') {
			$arrow_right = '<IMG SRC=assets/arrow_left.gif height=14 border=0>';
			$arrow_left = '<IMG SRC=assets/arrow_right.gif height=14 border=0>';
		}
		else {
			$arrow_right = '<IMG SRC=assets/arrow_right.gif height=14 border=0>';
			$arrow_left = '<IMG SRC=assets/arrow_left.gif height=14 border=0>';
		}

		if ($_REQUEST['all_assignments'] == 'true') {
			$end = count($assignments_RET);
			$all_assignments_link // = 
					= '<A HREF='
					. PreparePHP_SELF('',array('all_assignments'))
					. '&all_assignments=false><b>'
					. _('Show First 9 Assignments')
					. '</b>'.$arrow_left
					. '</A>'
					;
		}
		else {
			if (count($assignments_RET) > 9) {
				$end = 9;
				$all_assignments_link // =
						= '<A HREF='
						. PreparePHP_SELF('',array('all_assignments'))
						. '&all_assignments=true><b>'
						. _('Show All Assignments')
						. '</b>'
						. $arrow_right
						. '</A>'
						;
			}
			else {
				$end = count($assignments_RET);
			}
		}
		
		//foreach ($assignments_RET as $assignment)
		for($i = 1; $i <= $end; $i++) {
			$assignment = $assignments_RET[$i];
			$extra['SELECT'] .= ",'' AS G$assignment[ASSIGNMENT_ID]";
			$extra['functions'] += array('G'.$assignment['ASSIGNMENT_ID']=>'_makeExtraCols');
			$total_points[$assignment['ASSIGNMENT_ID']] = $assignment['POINTS'];
			$LO_columns += array
					(  'G'.$assignment['ASSIGNMENT_ID']
						=> "</b>" 
							. substr($assignment['TITLE'], 0, 6) 
							. "<br><b>(" . $assignment['POINTS'] . ")"
					);
		}
	}
}

if ($_REQUEST['values'] 
&& $_POST['values'] 
&& $_SESSION['assignment_id'] == $_REQUEST['assignment_id']
){
	foreach ($_REQUEST['values'] as $student_id => $assignments){
		foreach ($assignments as $assignment_id => $columns){
			if ($columns['POINTS']) {
				if ($columns['POINTS'] == '*') {
					$columns['POINTS'] = '-1';
				}
				$columns['POINTS'] = ereg_replace
						("[^0-9.-]"
						,''
						,$columns['POINTS']
						);
			}
			
			if ($current_RET[$student_id][$assignment_id]) {
				DBUpdate('GRADEBOOK_GRADES'
						, array(  'STUDENT_ID'       => $student_id 
								, 'ASSIGNMENT_ID'    => $assignment_id 
						  		, 'COURSE_PERIOD_ID' => $course_period_id
								)
						, array( $columns )
						);						
			}
			else {
				DBInsertInto('GRADEBOOK_GRADES'
						, array ( 'STUDENT_ID'       => $student_id
								, 'PERIOD_ID'        => UserPeriod()
								, 'COURSE_PERIOD_ID' => $course_period_id
								, 'ASSIGNMENT_ID'    => $assignment_id
								, 'POINTS'           => $columns['POINTS']
								, 'COMMENT'          => $columns['COMMENT']
								)
						);
			}
		}
	}
	if ($_REQUEST['student_id']) {
		$current_RET = DBGet(DBQuery("
				SELECT        ASSIGNMENT_ID
				 ,            POINTS
				 ,            STUDENT_ID 
				FROM          GRADEBOOK_GRADES 
				WHERE         STUDENT_ID = '$user_student_id' 
				 AND          COURSE_PERIOD_ID = '$course_period_id'
				"), array(), array('STUDENT_ID','ASSIGNMENT_ID'));
	}	
	elseif ($_REQUEST['assignment_id']) {
		$current_RET = DBGet(DBQuery("
				SELECT        STUDENT_ID
				 ,            POINTS
				 ,            COMMENT
				 ,            ASSIGNMENT_ID 
				FROM          GRADEBOOK_GRADES 
				WHERE         ASSIGNMENT_ID = '$_REQUEST[assignment_id]'
				 AND          COURSE_PERIOD_ID = '$course_period_id'
				"), array(), array('STUDENT_ID','ASSIGNMENT_ID'));
	}
	else {
		$current_RET = DBGet(DBQuery("
				SELECT        g.STUDENT_ID
				 ,            g.ASSIGNMENT_ID
				 ,            g.POINTS 
				FROM          GRADEBOOK_GRADES g
				 JOIN         GRADEBOOK_ASSIGNMENTS a 
				  ON          a.ASSIGNMENT_ID = g.ASSIGNMENT_ID 
				WHERE         a.MARKING_PERIOD_ID = '$user_mp' 
				 AND          g.COURSE_PERIOD_ID = '$course_period_id'
				"), array(), array('STUDENT_ID','ASSIGNMENT_ID'));
	}

	unset($_REQUEST['values']);
	unset($_SESSION['_REQUEST_vars']['values']);
}

$_SESSION['assignment_id'] = $_REQUEST['assignment_id'];

$assignment_select = '<SELECT name=assignment_id onchange="document.location.href=\'Modules.php?modname='.$_REQUEST['modname'].'&assignment_id=\'+this.options[selectedIndex].value"><OPTION value="">All</OPTION><OPTION value="totals"'.($_REQUEST['assignment_id']=='totals'?' SELECTED':'').'>'._('Totals').'</OPTION>';
$mass_update_assignment_select = '<SELECT name=mass_update_assignment_id width=8em><OPTION value="all">All</OPTION>';

if ($_REQUEST['student_id']) {
	$assignment_select .= '<OPTION value=student SELECTED>'._('Student').'</OPTION>';
}

if (count($assignments_RET)) {
	foreach ($assignments_RET as $assignment) {
		$assignment_select // .= 
				.= '<OPTION value='
						. $assignment['ASSIGNMENT_ID']
						. (($_REQUEST['assignment_id'] == $assignment['ASSIGNMENT_ID'])
							?' SELECTED'
							:'')
						.'>'
				. $assignment['TITLE'] 
				. '</OPTION>'
				;
				
		$mass_update_assignment_select // .= 
				.= '<OPTION value='
						. $assignment['ASSIGNMENT_ID']
						.'>'
				. substr($assignment['TITLE'], 0, 6) 
				. '</OPTION>'
				;
	}
}

$assignment_select .= '</SELECT>';
$mass_update_assignment_select .= '</SELECT>';

$assignment_select .= button
		( 'add'
		, _('Add an Assignment')
		, "javascript:switchMenu('add_div',false);doOnresize();"
		, "15 id=add_div_arrow"
		);

echo "<FORM action=Modules.php"
		. "?modname=$_REQUEST[modname]"
		. "&student_id=$_REQUEST[student_id]"
		. "&assignment_id=$_REQUEST[assignment_id] 
		method=POST>";

$mass_update_form = "
<div id='mass_update' align='left' style='white-space:nowrap;'>
	Mass update $mass_update_assignment_select <br/>
	change "
	. TextInput
			( ''
			, 'update_from'
			, ''
			, ' size=4 maxlength=4'
			)
	. " to "
	. TextInput
			( ''
			, 'update_to'
			, ''
			, ' size=4 maxlength=4'
			)
	. "
	&nbsp;&nbsp;
	<span style='color:maroon; cursor:pointer;'>[go]</span>
</div>
";

DrawHeader(_('Gradebook') . ' - ' . ProgramTitle());

DrawHeader
		( $assignment_select
		, $all_assignments_link . ' <INPUT type=submit value=' . _('Save') . '>'
		, $mass_update_form
		);
		

$RET = array();

if (!$_REQUEST['_FOCUS_PDF']) {
	echo "<DIV id=add_div style='display:none;'>";
	echo '<TABLE cellpadding=3 bgcolor=#F0F0F1 width=100%>';
	echo '<TR>';
	
	echo '<TD>' . TextInput
			( $RET['TITLE']
			, 'tables[TITLE]'
			, _('Title')
			) . '</TD>';
			
	echo '<TD>' . TextInput
			( $RET['POINTS']
			, 'tables[POINTS]'
			, _('Points')
			, ' size=4 maxlength=4'
			) . '</TD>';
			
	echo '<TD>' . CheckboxInput
			( $RET['COURSE_ID']
			, 'tables[COURSE_ID]'
			, _('Apply to all Periods for this Course')
			, ''
			, true
			) . '</TD>';
	
	foreach ($types_RET as $type) {
		$assignment_type_options[$type['ASSIGNMENT_TYPE_ID']] = $type['TITLE'];
	}
	
	echo '<TD>' . SelectInput
			( $RET['ASSIGNMENT_TYPE_ID']
				? $RET['ASSIGNMENT_TYPE_ID']
				: $_REQUEST['assignment_type_id']
			, 'tables[ASSIGNMENT_TYPE_ID]'
			, _('Assignment Type')
			, $assignment_type_options
			, false
			) . '</TD>';
					
	echo '</TR><TR>';
	
	echo '<TD valign=top>' . DateInput
			( DBDate()
			, 'tables[ASSIGNED_DATE]'
			, _('Assigned')
			, false
			) . '</TD>';
					
	echo '<TD valign=top>' . DateInput
			( DBDate()
			, 'tables[DUE_DATE]'
			, _('Due')
			, false
			) . '</TD>';
			
	echo '<TD colspan=2>' . TextareaInput
			( $RET['DESCRIPTION']
			, 'tables[DESCRIPTION]'
			, _('Description')
			) . '</TD>';
					
	echo '</TR>';
	echo '</TABLE>';
	
	echo '</DIV>';
	
	echo '<SCRIPT language=javascript>';
	echo 'function nextInput(e,form,tabindex)
		{
			if (e && e.which)
				key = e.which;
			else if (window.event) // ie
				key = window.event.keyCode;
	
			if (key==13)
			{
				count_elements = form.length;
				for(i=0;i<count_elements;i++)
				{
					if (form[i].tabIndex == tabindex)
					{
						next_field = i;
						form[next_field].select(); 
					} 
				} 
				return false;
			}
		}';
	echo '</SCRIPT>';
}

if (!$_REQUEST['student_id'])
{
	$stu_RET = GetStuList($extra);
	if (!$_REQUEST['student_id'])
	{
		$link['FULL_NAME']['link'] // =
				= "Modules.php"
				. "?modname=$_REQUEST[modname]"
				. "&assignment_id=student"
				;
				
		$link['FULL_NAME']['variables'] = array('student_id' => 'STUDENT_ID');
	}
	if (!$_REQUEST['student_id'] 
	&& !$_REQUEST['assignment_id']
	){
		$options = array('yscroll' => true);
	}

	ListOutput // (...)
			( $stu_RET
			, $LO_columns
			, _('Student')
			, _('Students')
			, $link
			, array()
			, $options
			);
}
else {
	$_REQUEST['course_period_id'] = UserCoursePeriod();
	include($staticpath.'/modules/Grades/StudentGBGrades.php');
}

echo '<IMG SRC=assets/pixel_trans.gif width=22>
<INPUT type=submit style="width:300;" value='._('Save').'>';

echo '<script language=javascript>
document.getElementById("LOy_layer").innerHTML += "<IMG SRC=assets/pixel_trans.gif height=30 width=22><INPUT type=submit style=\"width:300;\" value='._('Save').'>"
</script>';

//echo '<IMG SRC=assets/pixel_trans.gif width=160 height=1><INPUT type=submit value='._('Save').'>';
echo '</FORM>';
// so that teachers will be able to scroll down further ... this way the column headings will float closer to the current student.
echo '<BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>';

function _makeExtraAssnCols($value,$column)
{	global  $THIS_RET
	,       $total_points
	,       $current_RET
	,       $current_types_RET
	,       $percent_RET
	,       $programconfig
	,       $tabindex
	;

	switch($column)
	{
		case 'LETTER_GRADE':
			if ($_REQUEST['assignment_id'] == 'totals' 
			&& !$_REQUEST['student_id']
			){
				if ($programconfig['WEIGHT'] == 'Y' 
				&& count($percent_RET[$THIS_RET['STUDENT_ID']])
				){
					$total = 0;
					foreach ($percent_RET[$THIS_RET['STUDENT_ID']] as $type_id => $type) {
						$total += $type[1]['PARTIAL_PERCENT'];
					}
				}
				elseif ($current_RET[$THIS_RET['STUDENT_ID']][1]['TOTAL_POINTS']) {
					$total = $current_RET[$THIS_RET['STUDENT_ID']][1]['POINTS'] 
							/ $current_RET[$THIS_RET['STUDENT_ID']][1]['TOTAL_POINTS'];
				}
				else {
					$total = 0;
				}
				
				return Percent($total,0)
					. '&nbsp;'
					. _makeLetterGrade($total, UserCoursePeriod());
			}
			else {
				if ($current_RET[$THIS_RET['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS'] != '*') {
					return Percent($current_RET[$THIS_RET['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS'] / $total_points, 0) 
						.'&nbsp;'
						. _makeLetterGrade($current_RET[$THIS_RET['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS'] / $total_points, UserCoursePeriod());
				}
				else {
					return _('N/A').'&nbsp;'._('N/A');
				}
			}
			break;
		
		case 'COMMENT':
			return TextInput($current_RET[$THIS_RET['STUDENT_ID']][$_REQUEST['assignment_id']][1]['COMMENT']
					, 'values['.$THIS_RET['STUDENT_ID'].']['.$_REQUEST['assignment_id'].'][COMMENT]'
					, ''
					, ' maxlength=100 tabindex='.(500+$tabindex)
					);
			break;

		case 'POINTS':
		default:
			if ($column != 'POINTS')
				$assignment_type_id = substr($column,7);

			$tabindex++;
			if ($_REQUEST['assignment_id'] == 'totals' 
			&& !$_REQUEST['student_id'] 
			&& $column == 'POINTS'
			){
				$total_points // =
						= $current_RET[$THIS_RET['STUDENT_ID']][1]['TOTAL_POINTS'];
			}
			elseif ($_REQUEST['assignment_id'] == 'totals' 
			&& !$_REQUEST['student_id']
			){
				$total_points // =
						= $current_types_RET[$THIS_RET['STUDENT_ID']][$assignment_type_id][1]['TOTAL_POINTS'];
			}

			if ($current_RET[$THIS_RET['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS'] == -1) {
				$current_RET[$THIS_RET['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS'] = '*';
			}
			
			if ($_REQUEST['assignment_id'] != 'totals') {
				return '<TABLE border=0 cellspacing=0 cellpadding=0 class=innerLO_field><TR><TD>'
						. TextInput // (...)
								( ereg_replace
										( '\.$'
										, ''
										, (ereg_replace
												( '\.$'
												, ''
												, ((strpos($current_RET[$THIS_RET['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS'],'.') === false)
													? $current_RET[$THIS_RET['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS']
													: rtrim($current_RET[$THIS_RET['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS'],'0')
												  )
												)
										  )
										)
								, 'values['.$THIS_RET['STUDENT_ID'].']['.$_REQUEST['assignment_id'].'][POINTS]'
								, ''
								, ' style="width: 2.5em; font-family: Courier New, monospace;" size=1 maxlength=7 tabindex='.$tabindex.' onkeypress="return nextInput(event,this.form,'.($tabindex+1).');"'
								, !is_numeric($_REQUEST['assignment_id'])
								)
						. '</TD><!--<TD> &nbsp;&nbsp;&nbsp; </TD><TD>'
						. $total_points
						. '</TD>--></TR></TABLE>'
						;
			}
			else {
				if ($column == 'POINTS') {
					$points = $current_RET[$THIS_RET['STUDENT_ID']][1]['POINTS'];
				}
				else {
					$points = $current_types_RET[$THIS_RET['STUDENT_ID']][$assignment_type_id][1]['POINTS'];
				}
				
				return '<TABLE border=0 cellspacing=0 cellpadding=0 class=innerLO_field><TR><TD>'
						. (ereg_replace
								( '\.$'
								, ''
								, ((strpos($points,'.') === false)
									? $points
									: rtrim($points,'0')
								  )
								) * 1
							) 
						. '</TD><!--<TD> &nbsp;&nbsp;&nbsp; </TD><TD>'
						. $total_points 
						. '</TD><TD> &nbsp; '
						. Percent($points/$total_points, 0) 
						. '&nbsp;'
						. _makeLetterGrade(($points / $total_points) ,UserCoursePeriod())
						. '</TD>--></TR></TABLE>';
			}
		break;
	}
	
}

function _makeExtraStuCols($value,$column)
{	global $THIS_RET
	,      $total_points
	,      $current_RET
	;
	
	$assignment_id = substr($column,1);
	
	if ($current_RET[$_REQUEST['student_id']][$assignment_id][1]['POINTS'] == '-1') {
		$current_RET[$_REQUEST['student_id']][$assignment_id][1]['POINTS'] = '*';
	}
	
	$current_RET[$_REQUEST['student_id']][$assignment_id][1]['POINTS'] // =
		= ereg_replace
				( '\.$'
				, ''
				, ((strpos($current_RET[$_REQUEST['student_id']][$assignment_id][1]['POINTS'],'.') !== false)
					? rtrim($current_RET[$_REQUEST['student_id']][$assignment_id][1]['POINTS'],'0')
					: $current_RET[$_REQUEST['student_id']][$assignment_id][1]['POINTS']
				  )
				);	

	// IF THE NAME OF THE TEXT FIELDS EVER CHANGES, StudentGBGrades.php will also have to be changed to reflect this.  Current value: 'values['.$_REQUEST['student_id'].']['.$assignment_id.'][POINTS]'
	if ($current_RET[$_REQUEST['student_id']][$assignment_id][1]['POINTS'] != '*') {
		return '<TABLE border=0 cellspacing=0 cellpadding=0 class=innerLO_field><TR><TD>'
				. TextInput($current_RET[$_REQUEST['student_id']][$assignment_id][1]['POINTS']
						, 'values['.$_REQUEST['student_id'].']['.$assignment_id.'][POINTS]'
						, ''
						, ' style="width: 2.5em; font-family: Courier New, monospace;" size=1 maxlength=7'
						)
				. '</TD><!--<TD> &nbsp;&nbsp;&nbsp; </TD><TD>'.$total_points[$assignment_id].'</TD><TD>&nbsp;'
				. Percent($current_RET[$_REQUEST['student_id']][$assignment_id][1]['POINTS']/$total_points[$assignment_id],0) 
				. '&nbsp;'
				. _makeLetterGrade($current_RET[$_REQUEST['student_id']][$assignment_id][1]['POINTS']/$total_points[$assignment_id],UserCoursePeriod()).'</TD>--></TR></TABLE>';
	}
	else
		return '<TABLE border=0 cellspacing=0 cellpadding=0 class=innerLO_field><TR><TD>'
				. TextInput($current_RET[$_REQUEST['student_id']][$assignment_id][1]['POINTS']
						, 'values['.$_REQUEST['student_id'].']['.$assignment_id.'][POINTS]'
						, ''
						, ' style="width: 2.5em; font-family: Courier New, monospace;" size=1 maxlength=7'
						)
				. '</TD><!--<TD> &nbsp;&nbsp;&nbsp; </TD><TD>'
				. $total_points[$assignment_id]
				.'</TD><TD>&nbsp;'._('N/A').'&nbsp;'._('N/A')
				.'</TD>--></TR></TABLE>';
}

function _makeExtraCols($value,$column)
{	global $THIS_RET
	,      $total_points
	,      $current_RET
	,      $old_student_id
	,      $student_count
	,      $tabindex
	,      $count_students
	;
	
	if ($THIS_RET['STUDENT_ID'] != $old_student_id) {
 		$student_count++;
		$tabindex = $student_count;
		$old_student_id = $THIS_RET['STUDENT_ID'];
	}
	else {
		$tabindex += $count_students;
	}
	
	$assignment_id = substr($column,1);
	if ($current_RET[$THIS_RET['STUDENT_ID']][$assignment_id][1]['POINTS'] == '-1') {
		$current_RET[$THIS_RET['STUDENT_ID']][$assignment_id][1]['POINTS'] = '*';
	}
	
	$current_RET[$THIS_RET['STUDENT_ID']][$assignment_id][1]['POINTS'] // =
		= ereg_replace
			( '\.$'
			, ''
			, ((strpos($current_RET[$THIS_RET['STUDENT_ID']][$assignment_id][1]['POINTS'],'.')!==false)
				? rtrim($current_RET[$THIS_RET['STUDENT_ID']][$assignment_id][1]['POINTS'],'0')
				: $current_RET[$THIS_RET['STUDENT_ID']][$assignment_id][1]['POINTS'])
			);	

	if ($current_RET[$THIS_RET['STUDENT_ID']][$assignment_id][1]['POINTS']!='*')
		return '<TABLE border=0 cellspacing=0 cellpadding=0 class=innerLO_field><TR><TD>'
						. TextInput($current_RET[$THIS_RET['STUDENT_ID']][$assignment_id][1]['POINTS']
								, 'values['.$THIS_RET['STUDENT_ID'].']['.$assignment_id.'][POINTS]'
								, ''
								, ' style="width: 2.5em; font-family: Courier New, monospace;" size=1 maxlength=7 tabindex='.$tabindex.' onkeypress="return nextInput(event,this.form,'.($tabindex+1).');"'
								, ($_REQUEST['assignment_id'] && $_REQUEST['assignment_id']!='student')
						).'</TD><!--<TD> &nbsp;&nbsp;&nbsp; </TD><TD>'.$total_points[$assignment_id].'</TD><TD>&nbsp;'.Percent($current_RET[$THIS_RET['STUDENT_ID']][$assignment_id][1]['POINTS']/$total_points[$assignment_id],0) .'&nbsp;'. _makeLetterGrade($current_RET[$THIS_RET['STUDENT_ID']][$assignment_id][1]['POINTS']/$total_points[$assignment_id],UserCoursePeriod()).'</TD>--></TR></TABLE>';
	else
		return '<TABLE border=0 cellspacing=0 cellpadding=0 class=innerLO_field><TR><TD>'
						. TextInput($current_RET[$THIS_RET['STUDENT_ID']][$assignment_id][1]['POINTS']
								, 'values['.$THIS_RET['STUDENT_ID'].']['.$assignment_id.'][POINTS]'
								, ''
								, ' style="width: 2.5em; font-family: Courier New, monospace;" size=1 maxlength=7 tabindex='.$tabindex.' onkeypress="return nextInput(event,this.form,'.($tabindex+1).');"'
								, ($_REQUEST['assignment_id'] && $_REQUEST['assignment_id']!='student')
								).'</TD><!--<TD> &nbsp;&nbsp;&nbsp; </TD><TD>'.$total_points[$assignment_id].'</TD><TD>&nbsp;'._('N/A').'&nbsp;'._('N/A').'</TD>--></TR></TABLE>';
}
?>
